#!/bin/sh
. /lib/dracut-lib.sh
. /lib/kdump-lib-initramfs.sh

DUMP_RETVAL=$1
HOST_IP='127.0.0.1'

if [ "$DUMP_RETVAL" -ne 0 ]; then
	echo "Kdump have failed, not purging old dump"
fi

# Copied from kdump.sh
get_host_ip() {
	if is_nfs_dump_target || is_ssh_dump_target; then
		kdumpnic=$(getarg kdumpnic=)
		if [ -z "$kdumpnic" ]; then
			derror "failed to get kdumpnic!"
			return 1
		fi
		if ! kdumphost=$(ip addr show dev "$kdumpnic" | grep '[ ]*inet'); then
			derror "wrong kdumpnic: $kdumpnic"
			return 1
		fi
		kdumphost=$(echo "$kdumphost" | head -n 1 | awk '{print $2}')
		kdumphost="${kdumphost%%/*}"
		if [ -z "$kdumphost" ]; then
			derror "wrong kdumpnic: $kdumpnic"
			return 1
		fi
		HOST_IP=$kdumphost
	fi
	return 0
}

# $1: KDUMP_KEEP_OLD_DUMPS
# purge old dump directories if the number of directories
# exceeds KDUMP_KEEP_OLD_DUMPS
purge_old_dumps() {
	keep_old_dumps=$1
	kdump_mnt=$2
	kdump_path=$3

	# -2 (delete all dumps) means logic 0 here
	if [ "$keep_old_dumps" -eq -2 ]; then
		keep_old_dumps=0
	fi

	if [ -d "$kdump_mnt"/"$kdump_path" ]; then
		dump_path="$kdump_mnt"/"$kdump_path"
	elif [ -d "/sysroot/$kdump_path" ]; then
		dump_path="/sysroot/$kdump_path"
	else
		echo "Not purging dump: Unsupported dump target."
		exit 1
	fi
	echo "Purging dump in: $dump_path"
	dirs="$(find "$dump_path" -maxdepth 1 -type d -name "$HOST_IP-20*-*-*-*:*:*" | sort)"
	numdirs=$(echo "$dirs" | wc -l)
	echo "$dirs" | while read -r d; do
		if [ "$numdirs" -le $keep_old_dumps ]; then
			break
		fi
		echo " Expiring old dump $d"
		rm -rf "$d"
		numdirs=$((numdirs - 1))
	done
}

kdump_target=$(kdump_get_conf_val "ext[234]\|xfs\|btrfs\|minix\|nfs")
if [ -z "$kdump_target" ]; then
	echo "Not purging dump: Unsupported dump target."
	exit 1
fi

get_host_ip
kdump_mnt=$(get_mntpoint_from_target "$kdump_target")
kdump_path=$(get_save_path)
KDUMP_KEEP_OLD_DUMPS=$(kdump_get_conf_val "keep_old_dumps")

# special value 0 is used for "do nothing" and -1 is reserved
if [ "$KDUMP_KEEP_OLD_DUMPS" -gt 0 ] || [ "$KDUMP_KEEP_OLD_DUMPS" -lt -1 ]; then
	purge_old_dumps "$KDUMP_KEEP_OLD_DUMPS" "$kdump_mnt" "$kdump_path"
fi
